﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace QueryResource.TextFormat
{

    /// <summary>
    /// 将多个空格 替换成1个
    /// </summary>
    internal class ReplaceSpaceFormat : ITextFormat
    {
        public ReplaceSpaceFormat(bool isReplaceNewLine)
        {
            this.IsReplaceNewLine = isReplaceNewLine;
        }

        public bool IsReplaceNewLine { get; set; }

        #region ITextFormat 成员

        public string TextFormat(string sql)
        {
            if (sql == string.Empty)
                return string.Empty;
            if (IsReplaceNewLine)
            {
                //将原有的 的换行替换掉
                sql = sql.Replace(Environment.NewLine, "");
                sql = sql.Replace("\n", "");
                sql = sql.Replace("\r", "");

                //替换多余空格
                Regex r = new Regex(@" {2,}", RegexOptions.Multiline);
                if (r.IsMatch(sql))
                {
                    sql = r.Replace(sql, " ");
                }
            }
            List<string> list = new List<string> { 
                "select", 
                "where", 
                "from", 
                "left join", 
                "left outer join", 
                "right join", 
                "right outer join", 
                "order by", 
                "group by", 
                "union", 
                "union all" ,
                "inner join"
            };
            list.ForEach(o =>
            {
                //默认 string.Replace 是区分大小写的。所以这里改用 Microsoft.VisualBasic.Strings
                sql = Microsoft.VisualBasic.Strings.Replace(sql, o, Environment.NewLine + o, 1, -1, Microsoft.VisualBasic.CompareMethod.Text);
            });

            //替换掉 + 或 “
            if(sql.TrimStart()[0] == '"')
            {
                sql = sql.Remove(sql.IndexOf('"'), 1);
            }
            return sql.Replace("\" +\"", "").Replace("\" + \"","")
                .Replace("\t \"","").Replace("\t\"","")
                .Replace("\" +", "").Replace("\"+", "")
                .Replace("+\"", "").Replace("+ \"", "")
                .Replace("\";", "");
            
        }

        #endregion
    }
}
